package secondriver.springsubway.example.auc;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.Assert;

import secondriver.springsubway.example.auc.annotation.PermissionPoint;

public class AnnotationPermissionBeanPostProcessor implements BeanPostProcessor {

	private final Class<PermissionPoint> permissionPoint = PermissionPoint.class;

	private Set<String> point = new HashSet<String>();

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName)
			throws BeansException {
		PermissionPoint pp = AnnotationUtils.findAnnotation(bean.getClass(),
				permissionPoint);
		if (null != pp) {
			String value = pp.value();
			Assert.hasLength(value,
					"PermissionPoint value must not be null/''.");
			point.add(value);
		}
		HashSet<String> permissionPointValues = this
				.getPermissionPointValue(bean);
		point.addAll(permissionPointValues);
		System.out.println(point);
		return bean;
	}

	private HashSet<String> getPermissionPointValue(Object bean) {
		Method[] methods = bean.getClass().getDeclaredMethods();
		HashSet<String> values = new HashSet<String>(methods.length);
		for (Method m : methods) {
			PermissionPoint pp = AnnotationUtils.findAnnotation(m,
					permissionPoint);
			if (null != pp) {
				String value = pp.value();
				Assert.hasLength(value,
						"PermissionPoint value must not be null/''.");
				values.add(value);
			}
		}
		return values;
	}
}
